var cusIndexStat = {
    layerIndex: -1,
    title:'主要的内容'
};
$(function () {
    $.parser.parse(); // 解析整个页面
    var lastMonths = getLastMonthStartDate().substring(0, 7);//YYYY-MM-DD
    var lastYearMonth = getOneYearStartDate().substring(0, 7);
    $("#startDate").val(lastYearMonth);
    $("#endDate").val(lastMonths);
    laydate.render({
        elem : '#dateRange',
        type : 'month',
        theme: '#afcede',
        range : true,
        value: lastYearMonth+' - '+lastMonths,
        done: function(value, start, end){
            var startMonth = start.month<10?"0"+start.month:start.month;
            var endMonth = end.month<10?"0"+end.month:end.month;
            var startDate = start.year+"-"+startMonth;
            var endDate = end.year+"-"+endMonth;
            $("#startDate").val(startDate);
            $("#endDate").val(endDate);
        }
    });
    $HUI.combobox('#Hospital',
        {
            data:$.parseJSON($("#officeMap").val()),
            valueField:'value',
            textField:'text',
            onSelect:cusIndexStat.officeChange,
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var hospId = $('#hospitalId').val();
                if (hospId != "") {
                    $(this).combobox("setValue", hospId);
                    $(this).combobox('disable');
                } else {
                    var val = $(this).combobox("getData");
                    if (val.length == 2) {//如果就一个院区 加上全部=2
                        $(this).combobox("setValue", val[1].value);
                        cusIndexStat.officeChange(val[1]);
                        $("#oneOffice").val("yes");
                    } else {
                        $(this).combobox("setValue", "");
                        $("#oneOffice").val("no");
                    }
                }
            }
        } )
    $HUI.combobox('#LocDic',
        {
            data:$.parseJSON($("#departMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6
            //目前主任医师和科室无关联
            //onSelect:cusIndexStat.LocChange
        })
    $HUI.combobox('#QCDic',
        {
            data:$.parseJSON($("#entityMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                $(this).combobox("setValue", val[0].value);
            }
        })

    $('.panel-header').css({"background-color": "#FFFFFF","border": "none"})
    //绘制标统计表格
    cusIndexStat.initTable();

});
$('#search').on('click', function () {
    cusIndexStat.initTable();
});

cusIndexStat.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function(data){
        $('#LocDic').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}

cusIndexStat.columns = [
    {title: '指标分类', field: 'mainTitle', align: 'left', valign: 'middle', sortable: false,width:80},
    {title: '指标', field: 'secTitle', align: 'left', valign: 'middle', sortable: false,width:220},
    {title: '值', field: 'result', align: 'left', valign: 'middle', sortable: false,width:90,
        formatter:function(value,row,index){
            return "<a onclick='cusIndexStat.chlikEvent(&apos;"+row.secId+"&apos;,&apos;"+row.numerator+"&apos;,&apos;"+row.denominator+"&apos;)'>"+value+"</a>";
        },
    },
]

cusIndexStat.drawTable = function(tableData){
    $('#indexStatTable').bootstrapTable("destroy");
    this.$table =
        $('#indexStatTable').bootstrapTable({
            data:tableData,
            striped: false,//是否显示行间隔色
            showFooter: false,
            paginationLoop: false,
            sidePagination: 'client',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
            sortName: "patientNum",
            sortOrder: 'desc',// desc  asc
            maintainSelected: true,//设为true 为选中的状态
            cache: false,
            search: false, //搜索框
            columns: cusIndexStat.columns,
            resizable: true,
            onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                // $(".th-inner").css("font-weight","700");//表头字体加粗
                $("#indexStatTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                    $(this).attr("title",$(this).text());
                });
            },
            onLoadSuccess: function(){
                var data = $('#indexStatTable').bootstrapTable('getData', true);
            }
        });
    var data = $('#indexStatTable').bootstrapTable('getData', true)
    var tem=data[0]
    cusIndexStat.chlikEvent(tem.secId,tem.numerator,tem.denominator)
    this.$table.off("scroll")
    //合并单元格
    mergeCells(data, "mainTitle", 1, $('#indexStatTable'));
};
cusIndexStat.initTable = function(){
    //获取主页左侧表格数据
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/cusindexstat/selectIndexTableData", function (data) {
        cusIndexStat.drawTable(data);
    }, function (data) {
    });
    params.aHospID = Common_GetValue('Hospital');
    params.aQCEntity = Common_GetText('QCDic');
    params.entityId = Common_GetValue('QCDic');
    params.aLocDesc = replaceValue(Common_GetText('LocDic'));
    params.aLocID  = replaceValue(Common_GetValue('LocDic'));
    params.startDate = $('#startDate').val();
    params.endDate = $('#endDate').val();
    ajax.set(params);
    ajax.start();
};
cusIndexStat.chlikEvent = function (headerId,numerator,denominator){
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/cusindexstat/selectDetails", function (data) {
        cusIndexStat.title = data.title
        cusIndexStat.drawLocChart(data.locChartData)
        cusIndexStat.drawDocChart(data.DocChartData)
    }, function (data) {
    });
    params.startDate = $('#startDate').val();
    params.endDate = $('#endDate').val();
    params.headerId = headerId
    params.numerator = numerator
    params.denominator = denominator
    ajax.set(params);
    ajax.start();

    $('#title').panel({
        title: '<b style="color: #5a5a5a;font-size: 24px">' + cusIndexStat.title + '</b>',
        background: 'transparent',
        height: 10
    });
    $('.panel-header').css({"background-color": "#FFFFFF","border": "none","margin-top":"10px","padding":"0"})
}

cusIndexStat.drawDocChart = function (data) {
    var dataArr = data
    var datalen = dataArr.length
    var yName = ''
    var dataobj = []
    var type = 0
    for (var i = 0; i < datalen; i++) {
        var row = dataArr[i]
        var tobj = {}
        if (row.value.includes('%')){
            yName = "%"
            tobj.value = row.value.replace("%", "")
            tobj.oppValue = tobj.value-100;
            type = 1
        }else {
            tobj.value = row.value
        }
        tobj.name = row.docName
        tobj.docId = row.docId
        tobj.locId = row.locId
        tobj.entityId = row.entityId
        tobj.startDate = row.startDate
        tobj.endDate = row.endDate
        tobj.epIds = row.epIds
        tobj.epIdsOpp = row.epIdsOpp
        dataobj.push(tobj)
    }
    dataobj.sort(function (a, b) {
        return a.value - b.value
    });

    dataobj = dataobj.slice(0, 10);
    var xdata = [], ydata = [], ydata1 = []
    dataobj.forEach(function (item, index) {
        xdata.push(item.name);
        ydata.push({
            value: item.value,
            docId: item.docId,
            entityId: item.entityId,
            startDate: item.startDate,
            endDate: item.endDate,
            epIds: item.epIds,
            epIdsOpp: item.epIdsOpp
        })
        if (item.oppValue != null){
            ydata1.push({
                value: item.oppValue,
                docId: item.docId,
                entityId: item.entityId,
                startDate: item.startDate,
                endDate: item.endDate,
                epIds: item.epIds,
                epIdsOpp: item.epIdsOpp
            })
        }
    });
    var myChart = echarts.init(document.getElementById('DocChart'));

    // 指定图表的配置项和数据
    var option = {
        title: {
            text: '医生分布',
            left: 'left'
        },
        tooltip: {},
        legend: {},
        xAxis: {
            type: 'category',
            data: xdata
        },
        yAxis: {
            name: yName,
            max: 'dataMax'
        },
        series: [
            {
                type: 'bar',
                data: ydata,
                barMaxWidth: '40px',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: '#83bff6'},
                        {offset: 0.5, color: '#188df0'},
                        {offset: 1, color: '#188df0'}
                    ])
                },
            }
            ]
    };
    if (ydata1.length != 0){
        option.series[0].name = '百分比'
        option.series.push({
            name: '差异',
            type: 'bar',
            data: ydata1,
            barMaxWidth: '40px',
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#67c67d'},
                    {offset: 0.5, color: '#32d725'},
                    {offset: 1, color: '#13ac1f'}
                ])
            },
        })
    }

    myChart.clear();
    myChart.setOption(option);

    myChart.off('click')
    myChart.on('click', function (event) {
        var docId = event.data.docId
        var entityId = event.data.entityId
        var epIds = event.data.epIds
        var epIdsOpp = event.data.epIdsOpp
        var startDate = event.data.startDate
        var endDate = event.data.endDate
        var href = Sys.backendPath + "/analysis/cusindexstat/detailsIndex/"+docId+"/ /"+entityId+"/"+epIds+"/"+epIdsOpp+"/"+startDate+"/"+endDate+"/"+type
        layer.open({
            type: 2,
            title: ['<i class = "fa fa-list-ol"></i>&nbsp;医生：'+event.name,'padding-left:20px'],
            area:["90%","90%"],
            scrollbar: false,//为了禁止父页面滚动条滚动
            skin:'classfyLBStyle layer-ext-hisui',
            content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        });
    })
}

cusIndexStat.drawLocChart = function (data) {
    var dataArr = data
    var datalen = dataArr.length
    var yName = ''
    var dataobj = []
    var type = 0
    for (var i = 0; i < datalen; i++) {
        var row = dataArr[i]
        var tobj = {}
        if (row.value.includes('%')){
            yName = "%"
            tobj.value = row.value.replace("%", "")
            tobj.oppValue = tobj.value-100;
            type = 1
        }else {
            tobj.value = row.value
        }
        tobj.name = row.locDesc
        tobj.docId = row.docId
        tobj.locId = row.locId
        tobj.entityId = row.entityId
        tobj.startDate = row.startDate
        tobj.endDate = row.endDate
        tobj.epIds = row.epIds
        tobj.epIdsOpp = row.epIdsOpp
        dataobj.push(tobj)
        }
    dataobj.sort(function (a, b) {
        return a.value - b.value
    });

    dataobj = dataobj.slice(0, 10);
    var xdata = [], ydata = [], ydata1 = []
    dataobj.forEach(function (item, index) {
        xdata.push(item.name);
        ydata.push({
            value: item.value,
            locId: item.locId,
            entityId: item.entityId,
            startDate: item.startDate,
            endDate: item.endDate,
            epIds: item.epIds,
            epIdsOpp: item.epIdsOpp
        })
        if (item.oppValue != null){
            ydata1.push({
                value: item.oppValue,
                locId: item.locId,
                entityId: item.entityId,
                startDate: item.startDate,
                endDate: item.endDate,
                epIds: item.epIds,
                epIdsOpp: item.epIdsOpp
            })
        }
    });
    var myChart = echarts.init(document.getElementById('LocChart'));
    // 指定图表的配置项和数据
    var option = {
        title: {
            text: '科室分布',
            left: 'left'
        },
        tooltip: {},
        legend: {},
        xAxis: {
            type: 'category',
            data: xdata
        },
        yAxis: {
            name: yName,
            max: 'dataMax'
        },
        series: [
            {
                type: 'bar',
                data: ydata,
                barMaxWidth: '40px',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: '#83bff6'},
                        {offset: 0.5, color: '#188df0'},
                        {offset: 1, color: '#188df0'}
                    ])
                },
            }

            ]
    };
    if (ydata1.length != 0){
        option.series[0].name = '百分比'
        option.series.push({
            name: '差异',
            type: 'bar',
            data: ydata1,
            barMaxWidth: '40px',
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {offset: 0, color: '#67c67d'},
                    {offset: 0.5, color: '#32d725'},
                    {offset: 1, color: '#13ac1f'}
                ])
            },
        })
    }
    myChart.clear();
    myChart.setOption(option);
    myChart.off('click')
    myChart.on('click', function (event) {
        var epIds = event.data.epIds
        var epIdsOpp = event.data.epIdsOpp
        var locId = event.data.locId
        var entityId = event.data.entityId
        var startDate = event.data.startDate
        var endDate = event.data.endDate
        var href = Sys.backendPath + "/analysis/cusindexstat/detailsIndex/ /"+locId+"/"+entityId+"/"+epIds+"/"+epIdsOpp+"/"+startDate+"/"+endDate+"/"+type
        layer.open({
            type: 2,
            title: ['<i class = "fa fa-list-ol"></i>&nbsp;科室：'+event.name,'padding-left:20px'],
            area:["90%","90%"],
            scrollbar: false,//为了禁止父页面滚动条滚动
            skin:'classfyLBStyle layer-ext-hisui',
            content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
        });
    })
}

//取值
function Common_GetText()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框
        itmValue = $this.combobox('getText');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.attr("label");
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue =$this.attr("label");
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}


//值为全部替换为空
function replaceValue(text) {
    if ("全部"==text) {
        return ""
    }else {
        return text;
    }
}

//取值
function Common_GetValue()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}
/**
 * 合并单元格
 * @param data 原始数据（在服务端完成排序）
 * @param fieldName 合并属性名称
 * @param colspan 合并列
 * @param target 目标表格对象
 */
function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }
}